package com.wxapp.admin.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wxapp.admin.api.pojo.entity.CompanyDeptDO;
import com.wxapp.admin.api.pojo.entity.DeptDO;
import com.wxapp.admin.api.pojo.vm.userCDJ.PDeptSelectVm;
import com.wxapp.admin.api.pojo.vo.userCDJ.QDeptSelectVm;
import com.wxapp.admin.service.mapper.CompanyDeptMapper;
import com.wxapp.admin.service.mapper.DeptMapper;
import com.wxapp.admin.service.service.CompanyDeptService;
import com.wxapp.common.constant.base.IBaseService;
import com.wxapp.common.constant.pojo.vm.ResultVm;
import com.wxapp.common.util.check.CheckUtil;
import com.wxapp.common.util.menuTree.TreeUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lgl
 * @Description 公司部门
 * @Datetime 2022/11/18 16:07
 * @Modified By
 */
@Service
@RequiredArgsConstructor
public class CompanyDeptServiceImpl extends IBaseService implements CompanyDeptService {

    private final CompanyDeptMapper companyDeptMapper;

    private final DeptMapper deptMapper;
    @Override
    public ResultVm<List<PDeptSelectVm>> selectDept(QDeptSelectVm vm) {
        List<CompanyDeptDO> userCDJDOS = null;
        if (CheckUtil.isNotNullString(vm.getCompanyId())) {
            LambdaQueryWrapper<CompanyDeptDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CompanyDeptDO::getStatus, true).eq(CompanyDeptDO::getCompanyId, vm.getCompanyId()).isNotNull(CompanyDeptDO::getDeptId).select(CompanyDeptDO::getDeptId);
            userCDJDOS = companyDeptMapper.selectList(wrapper);
            if (CheckUtil.isNullList(userCDJDOS)) {
                return success(new ArrayList<>());
            }
        }
        LambdaQueryWrapper<DeptDO> query = new LambdaQueryWrapper<>();
        query.select(DeptDO::getId, DeptDO::getPid, DeptDO::getDeptName)
                .like(CheckUtil.isNotNullString(vm.getName()), DeptDO::getDeptName, vm.getName())
                .eq(CheckUtil.isNotNullString(vm.getPid()), DeptDO::getPid, vm.getPid())
                .eq(DeptDO::getStatus, true);
        if (CheckUtil.isNotNullList(userCDJDOS)) {
            query.in(DeptDO::getId, userCDJDOS.stream().map(s -> s.getDeptId()).collect(Collectors.toList()));
        }
       var deptList = deptMapper.selectList(query);
        List<PDeptSelectVm> iBaseMenuTrees =  TreeUtil.buildCopyTree(deptList,PDeptSelectVm::new,null);
        return success(iBaseMenuTrees);
    }
}
